﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Abp.Extension.CodeGenerater.Winform.Service.assembly
{
    public class AssemblyService
    {


        public AssemblyService(string dll)
        {
            Dll = Load(dll);
        }

        public Assembly Dll { get; set; }
        public List<Type> Types { get; set; }
        public Assembly Load(string path)
        {
            try
            {
                return Assembly.LoadFrom(path);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 反编译 得到程序集中所有的公共类型
        /// </summary>
        /// <returns></returns>
        public AssemblyService Decompiler()
        {
            if (Dll == null)
            {
                throw new Exception("程序集未加载！");
            }
            Types = Dll.GetExportedTypes().ToList();
            return this;
        }

        public bool CheckType(string name)
        {
            if (Types == null || Types.Count == 0)
            {
                return false;
            }
            var typeName = Types.Select(t => t.FullName).Where(n => n == name);
            if (typeName.Any())
            {
                return true;
            }
            return false;
        }

        public Type GetTypeByName(string name)
        {
            return Types.FirstOrDefault(t => t.FullName == name);
        }

    }
}
